package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Scanner;

/*
*
 * 客户端
*/
public class Client {

    private Socket socket;
    public Client() {

        try {

            System.out.println("正在链接客户端...");
            socket = new Socket("localhost", 8088);
//            socket = new Socket("129.213.93.116",8088);/**/
            System.out.println("与服务端建立链接...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void start() {
        try {
            //启动用来读取服务端消息的线程
            ServerHandler handler = new ServerHandler();
            Thread t  = new Thread(handler);
            t.setDaemon(true); //设置守护线程
            t.start();

            //输出
            OutputStream out = socket.getOutputStream();  //输入流
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8); //转换为字节
            BufferedWriter bw = new BufferedWriter(osw);   //缓冲加速（小车）
            PrintWriter pw = new PrintWriter(bw, true);  //按行输入

            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("请输入发送到服务器端的信息:");
                String user = scanner.nextLine();
                if ("exit".equals(user)) {
                    System.out.println("用户已退出");
                    break;
                }
                pw.println(user);
            }
        } catch (IOException e) {
            e.printStackTrace();//输出错误信息
        }finally {
            try {
                socket.close();//关闭socket，与服务端进行4次挥手
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    /**
     * 该线程负责读取服务端发送过来的消息
     */
    private class ServerHandler implements Runnable{
        public void run(){
            //获取输入流读取服务端发送过来的消息
            String line;
            try {
                InputStream in = socket.getInputStream();//input：读取写入
                InputStreamReader isr = new InputStreamReader(in);//字节转换为字符
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message = br.readLine())!= null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
